﻿#region Usings

using System;
using System.Data.Entity;
using System.Globalization;
using System.Reflection;
using System.Threading;
using System.Web.Mvc;
using System.Web.Routing;
using Ninject;
using Ninject.Web.Mvc;
using Omu.Awesome.Mvc;
using Rail.Net.Core.Interfaces.Data;
using Rail.Net.Core.Interfaces.Data.Cacheable;
using Rail.Net.Core.Interfaces.Services;
using Rail.Net.Data;
using Rail.Net.Data.Caching;
using Rail.Net.Services;

#endregion

namespace Rail.Net
{
    public class MvcApplication : NinjectHttpApplication
    {
        private IKernel _kernel;

        [Inject]
        public IDalContext DalContext { get; set; }

        [Inject]
        public IEpaService Epa { get; set; }
 

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
            filters.Add(new HandleErrorAttribute());
        }

        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                "Default", // Route name
                "{controller}/{action}/{id}", // URL with parameters
                new {controller = "Ticket", action = "Selection", id = UrlParameter.Optional} // Parameter defaults
                );

            routes.MapRoute(
                "Connection details route", // Route name
                "{controller}/{action}/{id}/{forwardDirection}", // URL with parameters
                new
                    {
                        controller = "Connection",
                        action = "Details",
                        id = UrlParameter.Optional,
                        forwardDirection = UrlParameter.Optional
                    } // Parameter defaults
                );
        }

        protected override void OnApplicationStarted()
        {
            base.OnApplicationStarted();

            //Database.SetInitializer<DataContext>(new DbInitializer());
            Database.SetInitializer<DataContext>(null);


            HtmlHelper.ClientValidationEnabled = true;
            HtmlHelper.UnobtrusiveJavaScriptEnabled = true;

            ViewEngines.Engines.Clear();
            ViewEngines.Engines.Add(new RazorViewEngine());
            ViewEngines.Engines.Add(new WebFormViewEngine());

            AreaRegistration.RegisterAllAreas();

            RegisterGlobalFilters(GlobalFilters.Filters);
            RegisterRoutes(RouteTable.Routes);

            //ControllerBuilder.Current.SetControllerFactory(new ErrorHandlingControllerFactory());

            ModelMetadataProviders.Current = new AwesomeModelMetadataProvider();


            //Epa.GetAvailabilityTest();

            DalContext.RuRepository.All();
            DalContext.StationRepository.AllDefaultsIncluded();
            DalContext.RelationRepository.AllDefaultsIncluded();
            DalContext.ContengentTrainLabelRepository.All();
            DalContext.ContengentTrainNumberRepository.All();
            DalContext.GlobalTrainLabelRepository.All();
            DalContext.GlobalTrainNumberRepository.All();
            DalContext.ReservableTrainLabelRepository.All();
            DalContext.ReservableTrainNumberRepository.All();
            DalContext.VirtualRuTrainNumberRepository.AllDefaultsIncluded();
            DalContext.AdministrationRepository.All();
            DalContext.TariffRepository.AllDefaultsIncluded();
            DalContext.PaymentOptionRepository.All();
            DalContext.DiscountOptionRepository.All();
        }


        protected override IKernel CreateKernel()
        {
            _kernel = new StandardKernel();
            _kernel.Load(Assembly.GetExecutingAssembly());

            //_kernel.Bind<DataContext>().ToMethod(c => new DataContext()).InThreadScope();
            _kernel.Bind<ICacheProvider>().To<WebCacheProvider>().InSingletonScope();
            _kernel.Bind<IRuRepository>().To<RuRepository>().InThreadScope();
            _kernel.Bind<IStationRepository>().To<StationRepository>().InThreadScope();
            _kernel.Bind<IRelationRepository>().To<RelationRepository>().InThreadScope();
            _kernel.Bind<IRelationRuRepository>().To<RelationRuRepository>().InThreadScope();
            _kernel.Bind<IRelationDescriptionRepository>().To<RelationDescriptionRepository>().InThreadScope();
            _kernel.Bind<IDistanceRepository>().To<DistanceRepository>().InThreadScope();
            _kernel.Bind<IPriceDistanceRepository>().To<PriceDistanceRepository>().InThreadScope();
            _kernel.Bind<IPriceDomesticRepository>().To<PriceDomesticRepository>().InThreadScope();
            _kernel.Bind<IPriceSerialRepository>().To<PriceSerialRepository>().InThreadScope();
            _kernel.Bind<IContengentTrainLabelRepository>().To<ContengentTrainLabelRepository>().InThreadScope();
            _kernel.Bind<IContengentTrainNumberRepository>().To<ContengentTrainNumberRepository>().InThreadScope();
            _kernel.Bind<IGlobalTrainLabelRepository>().To<GlobalTrainLabelRepository>().InThreadScope();
            _kernel.Bind<IGlobalTrainNumberRepository>().To<GlobalTrainNumberRepository>().InThreadScope();
            _kernel.Bind<IReservableTrainLabelRepository>().To<ReservableTrainLabelRepository>().InThreadScope();
            _kernel.Bind<IReservableTrainNumberRepository>().To<ReservableTrainNumberRepository>().InThreadScope();
            _kernel.Bind<IVirtualRuTrainNumberRepository>().To<VirtualRuTrainNumberRepository>().InThreadScope();
            _kernel.Bind<IAdministrationRepository>().To<AdministrationRepository>().InThreadScope();
            _kernel.Bind<ITariffRepository>().To<TariffRepository>().InThreadScope();
            _kernel.Bind<IPaymentOptionRepository>().To<PaymentOptionRepository>().InThreadScope();
            _kernel.Bind<IDiscountOptionRepository>().To<DiscountOptionRepository>().InThreadScope();
            _kernel.Bind<IDalContext>().To<DalContext>().InThreadScope();
            _kernel.Bind<IStationLookupService>().To<StationLookupService>();
            _kernel.Bind<IContengentService>().To<ContengentService>();
            _kernel.Bind<IEpaService>().To<EpaService>();
            _kernel.Bind<IProductService>().To<ProductService>();
            _kernel.Bind<ITransportPlanService>().To<TransportPlanService>();

            _kernel.Inject(this);
            return _kernel;
        }

        protected void Application_AcquireRequestState(object sender, EventArgs e)
        {
            if (Request.RequestContext.HttpContext.Session != null &&
                Request.RequestContext.HttpContext.Session["Culture"] != null)
            {
                var sessionCulture = Request.RequestContext.HttpContext.Session["Culture"].ToString();
                var ci = new CultureInfo(sessionCulture);
                Thread.CurrentThread.CurrentUICulture = ci;
                Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(ci.Name);
            }
        }
    }
}